package com.zhou.controller;

import com.alibaba.fastjson.JSON;
import com.zhou.bean.Message;
import com.zhou.mvc.ResponseBody;
import com.zhou.mvc.ResponseView;
import com.zhou.service.AdminService;
import com.zhou.service.AdminServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

public class AdminController {



    @ResponseBody("/login.do")
    public String login(HttpServletRequest req, HttpServletResponse resp){
        AdminService adminService = new AdminServiceImpl();
        //传参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //调用Service传参数 并获取结果
        boolean login = adminService.login(username, password);
        //根据结果 返回不同的数据给ajax
        Message message = null;
        if (login){
            message = new Message(0,"登录成功");
            //登录时间和ip的更新
            Date date = new Date();
            String ip = req.getRemoteAddr();
            adminService.updateLoginTime(username,date,ip);
            req.getSession().setAttribute("username",username);
        }else {
            message = new Message(-1,"登录失败");
        }
        //将数据转换为json
        String json = JSON.toJSONString(message);
        return json;
    }
    @ResponseView("/toLogin.do")
    public String toLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.getSession().invalidate();
        System.out.println( req.getSession().getAttribute("username"));
        return "/admin/login.html";
    }
}
